package com.seari.controller;

import com.seari.bean.DeviceList;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.seari.bean.DeviceType;
import com.seari.bean.DeviceTypeAttr;
import com.seari.pojo.MessageBean;
import com.seari.pojo.QueryDeviceList;
import com.seari.pojo.QueryDeviceType;
import com.seari.service.DeviceListService;
import com.seari.service.DeviceTypeAttrService;
import com.seari.service.DeviceTypeService;
import com.seari.utils.DeviceListHelper;
import com.seari.utils.FEPDeviceListHelper;
import com.seari.utils.MiscTools;
import com.seari.utils.StringHelper;
import com.seari.utils.excel.ImportExcelUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashSet;
import java.util.logging.Level;
import org.springframework.util.CollectionUtils;

@Controller
@RequestMapping("excel/")
public class ExcelController
{
	private static final Logger logger = Logger.getLogger(ExcelController.class);
	static final String TYPE_CFGFILE = "excel_type.cfg";
	static final String LIST_CFGFILE = "excel_list.cfg";

	@Autowired
	private DeviceTypeService dts;

	@Autowired
	private DeviceTypeAttrService dtas;

	@Autowired
	private DeviceListService dls;

	@RequestMapping(value = "uploadDpType")
	@ResponseBody
	public MessageBean uploadDpType(@RequestParam("excel_file") CommonsMultipartFile file, HttpServletRequest req)
	{
		Properties config = null;
		config = configInit(config, TYPE_CFGFILE);
		MessageBean result = new MessageBean();
		result.setMessage("");
		String line = (String) req.getSession().getAttribute("LineID");
		List<List<Object>> listob = null;
		InputStream in = null;
		DeviceType deviceType = null;
		String fileName = req.getParameter("file_name");
		if (file.isEmpty() || StringUtils.isBlank(fileName))
		{
			result.setType(StringHelper.MESSAGE_TYPE_ERROR);
			result.setMessage("文件未上传");
		} else if (null == config)
		{
			result.setType(StringHelper.MESSAGE_TYPE_ERROR);
			result.setMessage("配置初始化失败");
		} else
		{
			try
			{
				if (!fileName.contains("_"))
				{
					result.setType(StringHelper.MESSAGE_TYPE_ERROR);
					result.setMessage("文件名缺少分隔符");
					return result;
				}
				fileName = fileName.substring(0, fileName.indexOf("_"));
				if ("BAS".equals(fileName.toUpperCase()))
				{
					fileName = "EMCS";
				}
				in = file.getInputStream();
				Map<String, List<List<Object>>> sheetMap = new ImportExcelUtil().getBankListByExcelReturnMap(in,
						file.getOriginalFilename());
				for (Entry<String, List<List<Object>>> entry : sheetMap.entrySet())
				{
					if ("CLASS".equals(entry.getKey().toUpperCase()))
					{
						continue;
					}
					deviceType = new DeviceType();
					List<DeviceTypeAttr> attrList = new ArrayList<DeviceTypeAttr>();
					deviceType.setDeviceName(fileName.toUpperCase() + "_" + entry.getKey());
					// 查询是否存在同名deviceType
					Integer resultNum = dts.getDeviceIdByName(deviceType.getDeviceName(), line);
					if (null != resultNum && resultNum > 0)
					{
						logger.info("已存在此条记录");
						deviceType.setTid(resultNum);
					} else
					{
						dts.addDeviceType(deviceType, line);
					}
					listob = entry.getValue();
					for (int i = 2; i < listob.size(); i++)
					{
						DeviceTypeAttr attr = new DeviceTypeAttr();
						List<Object> objList = listob.get(i);
						if (objList.size() < 1 || StringUtils.isBlank(objList.get(0).toString()))
						{
							break;
						}
						try
						{
							attr.setTid(deviceType.getTid());
							attr.setDeviceName(deviceType.getDeviceName());
							attr.setType(getListValueString(objList, Integer.parseInt(config.getProperty("type"))));
							attr.setIndex(getListValueString(objList, Integer.parseInt(config.getProperty("index"))));
							attr.setDesc(getListValueString(objList, Integer.parseInt(config.getProperty("desc"))));
							attr.setIoType(getListValueString(objList, Integer.parseInt(config.getProperty("io_type"))));
							attr.setDataType(getListValueString(objList, Integer.parseInt(config.getProperty("data_type"))));
							attr.setDigit0(getListValueString(objList, Integer.parseInt(config.getProperty("digit0"))));
							attr.setDigit1(getListValueString(objList, Integer.parseInt(config.getProperty("digit1"))));
							attr.setDigit2(getListValueString(objList, Integer.parseInt(config.getProperty("digit2"))));
							attr.setDigit3(getListValueString(objList, Integer.parseInt(config.getProperty("digit3"))));
							attr.setDigit4(getListValueString(objList, Integer.parseInt(config.getProperty("digit4"))));
							attr.setDigit5(getListValueString(objList, Integer.parseInt(config.getProperty("digit5"))));
							attr.setDigit6(getListValueString(objList, Integer.parseInt(config.getProperty("digit6"))));
							attr.setDigit7(getListValueString(objList, Integer.parseInt(config.getProperty("digit7"))));
							attr.setUnit(getListValueString(objList, Integer.parseInt(config.getProperty("unit"))));
							attr.seteControl(getListValueString(objList, Integer.parseInt(config.getProperty("e_control"))));
							attr.setEngk(getListValueString(objList, Integer.parseInt(config.getProperty("engk"))));
							attr.setEngHigh(getListValueString(objList, Integer.parseInt(config.getProperty("eng_high"))));
							attr.setEngLow(getListValueString(objList, Integer.parseInt(config.getProperty("eng_low"))));
							attr.seteAlarm(getListValueString(objList, Integer.parseInt(config.getProperty("e_alarm"))));
							attr.seteEvent(getListValueString(objList, Integer.parseInt(config.getProperty("e_event"))));
							attr.seteTrend(getListValueString(objList, Integer.parseInt(config.getProperty("e_trend"))));
							attr.seteTrendTime(getListValueString(objList, Integer.parseInt(config.getProperty("e_trend_time"))));
							attr.setDeadZone(getListValueString(objList, Integer.parseInt(config.getProperty("dead_zone"))));
							attr.setIfWire(getListValueString(objList, Integer.parseInt(config.getProperty("if_wire"))));
							attr.setAlarmType(getListValueString(objList, Integer.parseInt(config.getProperty("alarm_type"))));
							attr.setAlarmLevel(getListValueString(objList, Integer.parseInt(config.getProperty("alarm_level"))));
							attr.setAlarmHH(getListValueString(objList, Integer.parseInt(config.getProperty("alarm_hh"))));
							attr.setAlarmH(getListValueString(objList, Integer.parseInt(config.getProperty("alarm_h"))));
							attr.setAlarmL(getListValueString(objList, Integer.parseInt(config.getProperty("alarm_l"))));
							attr.setAlarmLL(getListValueString(objList, Integer.parseInt(config.getProperty("alarm_ll"))));
							attr.seteReport(getListValueString(objList, Integer.parseInt(config.getProperty("e_report"))));
							attr.seteEAM(getListValueString(objList, Integer.parseInt(config.getProperty("e_eam"))));
							attr.seteCenter(getListValueString(objList, Integer.parseInt(config.getProperty("e_center"))));
							attr.setIscsInfo(getListValueString(objList, Integer.parseInt(config.getProperty("iscs_info"))));
							attr.setIscsAddr(getListValueString(objList, Integer.parseInt(config.getProperty("iscs_addr"))));
							attr.setIscsBit(getListValueString(objList, Integer.parseInt(config.getProperty("iscs_bit"))));
							attr.setPlcInfo(getListValueString(objList, Integer.parseInt(config.getProperty("plc_info"))));
							attr.setIoSource(getListValueString(objList, Integer.parseInt(config.getProperty("io_source"))));
							attr.setComAddr(getListValueString(objList, Integer.parseInt(config.getProperty("com_addr"))));
							attr.setComBit(getListValueString(objList, Integer.parseInt(config.getProperty("com_bit"))));
							attrList.add(attr);
						} catch (IndexOutOfBoundsException e)
						{
							e.printStackTrace();
							String msg = result.getMessage() + "\n" + entry.getKey() + " 下标越界";
							if (objList.size() > Integer.parseInt(config.getProperty("type")))
							{
								msg += ",属性（type）:" + attr.getType();
							}
							result.setMessage(msg);
							logger.warn(msg);
							continue;
						}

						System.out.println(attr.toString());
					}
					deviceType.setAttrList(attrList);
					dtas.deleteAttrByTypeId(deviceType.getTid(), line);
					dtas.addDeviceAttr(deviceType.getAttrList(), line);
				}
				result.setType(StringHelper.MESSAGE_TYPE_SUCCESS);
				result.setMessage(result.getMessage() + "\n导入成功");

			} catch (Exception e)
			{
				if (deviceType != null)
				{
					logger.info("error device type is:" + deviceType.toString());
				}

				e.printStackTrace();
			}
		}
		return result;
	}

	@RequestMapping(value = "uploadDpList")
	@ResponseBody
	public MessageBean uploadDpList(@RequestParam("excel_file") CommonsMultipartFile file, HttpServletRequest req)
	{
		MessageBean result = new MessageBean();
		String line = (String) req.getSession().getAttribute("LineID");
		if (StringUtils.isBlank(line))
		{
			result.setType(StringHelper.MESSAGE_TYPE_ERROR);
			result.setMessage("线路ID为空，请重新登陆");
			return result;
		}
		Properties config = null;
		config = configInit(config, LIST_CFGFILE);
		result.setMessage(" ");
		String fileName = req.getParameter("file_name");
		List<List<Object>> listob = null;
		InputStream in = null;
		DeviceList deviceList = null;
		if (file.isEmpty())
		{
			result.setType(StringHelper.MESSAGE_TYPE_ERROR);
			result.setMessage("文件未上传");
		} else if (null == config)
		{
			result.setType(StringHelper.MESSAGE_TYPE_ERROR);
			result.setMessage("配置初始化失败");
		} else
		{
			try
			{
				if (!fileName.contains("_"))
				{
					result.setType(StringHelper.MESSAGE_TYPE_ERROR);
					result.setMessage("文件名缺少分隔符");
					return result;
				}
				try
				{
					fileName = fileName.substring(fileName.indexOf("_") + 1);
					fileName = fileName.substring(0, fileName.indexOf("_"));
				} catch (Exception e)
				{
					e.printStackTrace();
					result.setType(StringHelper.MESSAGE_TYPE_ERROR);
					result.setMessage("文件名格式错误");
					return result;
				}
				if ("BAS".equals(fileName.toUpperCase()))
				{
					fileName = "EMCS";
				}
				in = file.getInputStream();
				Map<String, List<List<Object>>> sheetMap = new ImportExcelUtil().getBankListByExcelReturnMap(in,
						file.getOriginalFilename());
				for (Entry<String, List<List<Object>>> entry : sheetMap.entrySet())
				{
					if ("修改记录".equals(entry.getKey()))
					{
						continue;
					}
					// 遍历sheet
					List<DeviceList> modifyList = new ArrayList<DeviceList>();
					List<DeviceList> deleteList = new ArrayList<DeviceList>();
					List<DeviceList> checkList = new ArrayList<DeviceList>();
					listob = entry.getValue();
					for (int i = 2; i < listob.size(); i++)
					{
						// 遍历所有行，有空行时跳出循环
						deviceList = new DeviceList();
						List<Object> objList = listob.get(i);
						if (objList.size() < 1)
						{
							// 行为空时，跳出循环
							break;
						}
						try
						{
							deviceList.setModifyID(
									getListValueString(objList, Integer.parseInt(config.getProperty("modify_id"))));
							deviceList.setSeqNum(
									getListValueString(objList, Integer.parseInt(config.getProperty("seq_num"))));
							deviceList.setDevIndex(
									getListValueString(objList, Integer.parseInt(config.getProperty("dev_index"))));
							deviceList.setLineID(
									getListValueString(objList, Integer.parseInt(config.getProperty("line_id"))));
							deviceList.setStationID(
									getListValueString(objList, Integer.parseInt(config.getProperty("station_id"))));
							deviceList.setSysID(
									getListValueString(objList, Integer.parseInt(config.getProperty("sys_id"))));
							deviceList.setDevID(fileName + "_"
									+ getListValueString(objList, Integer.parseInt(config.getProperty("dev_id"))));
							deviceList.setDevArea(
									getListValueString(objList, Integer.parseInt(config.getProperty("dev_area"))));
							deviceList.setDevNO(
									getListValueString(objList, Integer.parseInt(config.getProperty("dev_no"))));
							deviceList.setDevName(
									getListValueString(objList, Integer.parseInt(config.getProperty("dev_name"))));
							deviceList.setDevAddress(
									getListValueString(objList, Integer.parseInt(config.getProperty("dev_address"))));
							deviceList
									.setSbdm(getListValueString(objList, Integer.parseInt(config.getProperty("sbdm"))));
							deviceList.setLockOption(
									getListValueString(objList, Integer.parseInt(config.getProperty("lock_option"))));
							deviceList.setBoxID(
									getListValueString(objList, Integer.parseInt(config.getProperty("box_id"))));
							deviceList.setModuleTake(
									getListValueString(objList, Integer.parseInt(config.getProperty("module_take"))));
							deviceList.setDeviceSequence(getListValueString(objList,
									Integer.parseInt(config.getProperty("device_sequence"))));
							deviceList.setBeizhu1(
									getListValueString(objList, Integer.parseInt(config.getProperty("beizhu1"))));
							deviceList.setBeizhu2(
									getListValueString(objList, Integer.parseInt(config.getProperty("beizhu2"))));
							deviceList.setBeizhu3(
									getListValueString(objList, Integer.parseInt(config.getProperty("beizhu3"))));
							deviceList.setDriverType(
									getListValueString(objList, Integer.parseInt(config.getProperty("driver_type"))));
							deviceList.setUniqueStr(
									deviceList.getStationID() + "_" + fileName + "_" + deviceList.getSeqNum());
						} catch (IndexOutOfBoundsException e)
						{
							e.printStackTrace();
							String msg = result.getMessage() + "\n" + entry.getKey() + " 下标越界";
							if (objList.size() > Integer.parseInt(config.getProperty("dev_index")))
							{
								msg += ",设备编号（devIndex）:" + deviceList.getDevIndex();
							}
							result.setMessage(msg);
							logger.warn(msg);
							continue;
						}
						checkList.add(deviceList);
						if (DeviceListHelper.MODIFY_FLAG.equals(deviceList.getModifyID()))
						{
							modifyList.add(deviceList);
						} else if (DeviceListHelper.DELETE_FLAG.equals(deviceList.getModifyID()))
						{
							deleteList.add(deviceList);
						}
					}
					if (!checkDeviceLists(checkList, result))
					{
						result.setType(StringHelper.MESSAGE_TYPE_ERROR);
						return result;
					}
					if (!CollectionUtils.isEmpty(modifyList))
					{
						dls.insertOrUpdateDeviceList(modifyList, line);
					}
					if (!CollectionUtils.isEmpty(deleteList))
					{
						dls.deleteDeviceListByDeviceIndex(deleteList, line);
					}
				}
				result.setType(StringHelper.MESSAGE_TYPE_SUCCESS);
				result.setMessage(result.getMessage() + "\n导入成功");

			} catch (Exception e)
			{
				if (deviceList != null)
				{
					logger.info("error device type is:" + deviceList.toString());
				}
				e.printStackTrace();
			}
		}
		return result;
	}

	@RequestMapping(value = "downloadDpType")
	public void downLoadDeviceType(HttpServletRequest req, HttpServletResponse resp)
	{
		byte[] result = null;
		InputStream in = null;
		int currentRow = 4;
		int numSeq = 2;
		QueryDeviceType qdt = new QueryDeviceType();
		String line = (String) req.getSession().getAttribute("LineID");
		qdt.setLine(line);
		String ids = req.getParameter("ids");
		if (StringUtils.isNotBlank(ids))
		{
			qdt.setIds(ids);
		}
		List<DeviceType> dpList = dts.getDeviceTypeByParams(qdt);
		// 生成EXCEL固定的前4-5行
		Workbook wb = new XSSFWorkbook();
		Sheet sheet = wb.createSheet();
		Row row = sheet.createRow(0);
		row.createCell(0).setCellValue("# ascii dump of database");
		sheet.createRow(1);// 空行
		sheet.createRow(2).createCell(0).setCellValue("# DpType");
		sheet.createRow(3).createCell(0).setCellValue("TypeName");
		for (DeviceType deviceType : dpList)
		{
			Map<String, List<DeviceTypeAttr>> attrMap = new HashMap<String, List<DeviceTypeAttr>>();
			sheet.createRow(currentRow).createCell(0)
					.setCellValue(deviceType.getDeviceName() + "." + deviceType.getDeviceName());
			sheet.getRow(currentRow).createCell(1).setCellValue("1#1");
			numSeq = 2;
			currentRow++;
			for (DeviceTypeAttr attr : deviceType.getAttrList())
			{
				String attrType = attr.getType();
				if (attrMap.containsKey(attrType))
				{
					List<DeviceTypeAttr> attrList = attrMap.get(attrType);
					attrList.add(attr);
				} else
				{
					List<DeviceTypeAttr> attrList2 = new ArrayList<DeviceTypeAttr>();
					attrList2.add(attr);
					attrMap.put(attrType, attrList2);
				}
			}
			for (Entry<String, List<DeviceTypeAttr>> entry : attrMap.entrySet())
			{
				Row newRow = sheet.createRow(currentRow);
				// 取出的KEY为attr的type,单列一行,并且以1#开头
				newRow.createCell(0);
				newRow.createCell(1).setCellValue(entry.getKey());
				newRow.createCell(2).setCellValue("1#" + numSeq);
				numSeq++;
				currentRow++;
				for (DeviceTypeAttr attr : entry.getValue())
				{
					Row newRow2 = sheet.createRow(currentRow);
					newRow2.createCell(0);
					newRow2.createCell(1);
					newRow2.createCell(2).setCellValue(attr.getIndex());
					String dataType = DeviceListHelper.getAttrDataType(attr.getDataType());
					newRow2.createCell(3).setCellValue(dataType + "#" + numSeq);
					numSeq++;
					currentRow++;
				}
			}

		}
		resp.setHeader("content-disposition", "attachment;filename=dptype.xlsx");
		try
		{
			try (OutputStream outputStream = resp.getOutputStream())
			{
				wb.write(outputStream);
				outputStream.flush();
			}
			wb.close();
		} catch (IOException ex)
		{
			logger.error(ex);
		} finally
		{
			try
			{
				wb.close();
			} catch (IOException ex)
			{
				logger.error(ex);
			}
		}
	}

	@RequestMapping(value = "downloadDpList")
	public void downloadDpList(HttpServletRequest req, HttpServletResponse resp)
	{
		MessageBean messageBean = new MessageBean();
		messageBean.setMessage("");
		QueryDeviceList qdl = new QueryDeviceList();
		String line = (String) req.getSession().getAttribute("LineID");
		qdl.setLine(line);
		String ids = req.getParameter("ids");
		String station = req.getParameter("station");
		String system = req.getParameter("system");
		String devID = req.getParameter("devID");
		String devName = req.getParameter("devName");
		String from = req.getParameter("from");
		String to = req.getParameter("to");
		if (StringUtils.isNotBlank(from))
		{
			qdl.setFrom(Timestamp.valueOf(from));
		}
		if (StringUtils.isNotBlank(to))
		{
			qdl.setFrom(Timestamp.valueOf(to));
		}
		qdl.setIds(ids);
		if (StringUtils.isNotBlank(devID))
		{
			String[] devIDs = devID.split(",");
			qdl.setDevID(CollectionUtils.arrayToList(devIDs));
		}
		qdl.setDevName(devName);
		qdl.setStation(station);
		if (StringUtils.isNotBlank(system))
		{
			String[] systems = system.split(",");
			qdl.setSystem(CollectionUtils.arrayToList(systems));
		}
		List<DeviceList> deviceLists = dls.getDeviceListByParams(qdl);
		List<DeviceList> exportList = new ArrayList<DeviceList>();
		Map<String, DeviceType> deviceTypeMap = new HashMap<String, DeviceType>();
		for (DeviceList deviceList : deviceLists)
		{
			QueryDeviceType qdt = new QueryDeviceType();
			qdt.setDeviceName(deviceList.getDevID());
                        qdt.setLine(line);
			List<DeviceType> deviceTypes = dts.getDeviceTypeByParams(qdt);
			if (!CollectionUtils.isEmpty(deviceTypes))
			{
				DeviceType deviceType = deviceTypes.get(0);
				deviceList.setDeviceType(deviceType);
				exportList.add(deviceList);
				if (!deviceTypeMap.containsKey(deviceType.getDeviceName()))
				{
					deviceTypeMap.put(deviceType.getDeviceName(), deviceType);
				}
			} else
			{
				messageBean.appendMessage(deviceList.getDevIndex() + "缺少此DeviceType");
			}
		}
		DeviceListHelper dlh = new DeviceListHelper();
		Workbook wb = dlh.generateWorkBook(deviceTypeMap, exportList , line);
		resp.setHeader("content-disposition", "attachment;filename=dplist.xlsx");
		try
		{
			try (OutputStream outputStream = resp.getOutputStream())
			{
				wb.write(outputStream);
				outputStream.flush();
			}
		} catch (IOException ex)
		{
			logger.error(ex);
		} finally
		{
			try
			{
				wb.close();
			} catch (IOException ex)
			{
				logger.error(ex);
			}
		}
	}
	
	@RequestMapping(value = "downloadFEPDpList")
	public void downloadFEPDpList(HttpServletRequest req, HttpServletResponse resp)
	{
		MessageBean messageBean = new MessageBean();
		messageBean.setMessage("");
		QueryDeviceList qdl = new QueryDeviceList();
		String line = (String) req.getSession().getAttribute("LineID");
		qdl.setLine(line);
		String ids = req.getParameter("ids");
		String station = req.getParameter("station");
		String system = req.getParameter("system");
		String devID = req.getParameter("devID");
		String devName = req.getParameter("devName");
		String from = req.getParameter("from");
		String to = req.getParameter("to");
		if (StringUtils.isNotBlank(from))
		{
			qdl.setFrom(Timestamp.valueOf(from));
		}
		if (StringUtils.isNotBlank(to))
		{
			qdl.setFrom(Timestamp.valueOf(to));
		}
		qdl.setIds(ids);
		if (StringUtils.isNotBlank(devID))
		{
			String[] devIDs = devID.split(",");
			qdl.setDevID(CollectionUtils.arrayToList(devIDs));
		}
		qdl.setDevName(devName);
		qdl.setStation(station);
		if (StringUtils.isNotBlank(system))
		{
			String[] systems = system.split(",");
			qdl.setSystem(CollectionUtils.arrayToList(systems));
		}
		List<DeviceList> deviceLists = dls.getDeviceListByParams(qdl);
		List<DeviceList> exportList = new ArrayList<DeviceList>();
		Map<String, DeviceType> deviceTypeMap = new HashMap<String, DeviceType>();
		for (DeviceList deviceList : deviceLists)
		{
			QueryDeviceType qdt = new QueryDeviceType();
			qdt.setDeviceName(deviceList.getDevID());
                        qdt.setLine(line);
			List<DeviceType> deviceTypes = dts.getDeviceTypeByParams(qdt);
			if (!CollectionUtils.isEmpty(deviceTypes))
			{
				DeviceType deviceType = deviceTypes.get(0);
				deviceList.setDeviceType(deviceType);
				exportList.add(deviceList);
				if (!deviceTypeMap.containsKey(deviceType.getDeviceName()))
				{
					deviceTypeMap.put(deviceType.getDeviceName(), deviceType);
				}
			} else
			{
				messageBean.appendMessage(deviceList.getDevIndex() + "缺少此DeviceType");
			}
		}
		FEPDeviceListHelper flh = new FEPDeviceListHelper();
		Workbook wb = flh.generateWorkBook(deviceTypeMap, exportList , line);
		resp.setHeader("content-disposition", "attachment;filename=FEPdplist.xlsx");
		try
		{
			try (OutputStream outputStream = resp.getOutputStream())
			{
				wb.write(outputStream);
				outputStream.flush();
			}
		} catch (IOException ex)
		{
			logger.error(ex);
		} finally
		{
			try
			{
				wb.close();
			} catch (IOException ex)
			{
				logger.error(ex);
			}
		}
	}

	// 获取集合元素值，返回String
	private String getListValueString(List list, int index)
	{
		String result = "";
		if (!CollectionUtils.isEmpty(list))
		{
			if (list.size() <= index)
			{
				// throw new IndexOutOfBoundsException("集合下标越界");
			} else
			{
				result = list.get(index).toString().trim();
			}
		}
		return result;
	}


	private boolean checkDeviceLists(List<DeviceList> deviceLists, MessageBean mb)
	{
		HashSet<String> hashSet1 = new HashSet<>(); // seqNum
		HashSet<String> hashSet2 = new HashSet<>(); // devIndex
		HashSet<String> hashSet3 = new HashSet<>(); // uniqueStr
		int i = 3;
		for (DeviceList deviceList : deviceLists)
		{
			if (StringUtils.isBlank(deviceList.getSeqNum()) || StringUtils.isBlank(deviceList.getDevIndex())
					|| StringUtils.isBlank(deviceList.getUniqueStr()))
			{
				mb.setMessage("序号,编号,识别码部分为空 此行可能为空行.行号:" + i);
				mb.appendMessage(" 请删除空行后重试");
				return false;
			}
			if (!hashSet1.add(deviceList.getSeqNum()))
			{
				mb.setMessage("序号重复：" + deviceList.getSeqNum());
				mb.appendMessage(" 行号" + i + " " + deviceList.toString());
				return false;
			}
			if (!hashSet2.add(deviceList.getDevIndex()))
			{
				mb.setMessage("设备编号重复：" + deviceList.getDevIndex());
				mb.appendMessage(" 行号" + i + " " + deviceList.toString());
				return false;
			}
			if (!hashSet3.add(deviceList.getUniqueStr()))
			{
				mb.setMessage("识别码重复：" + deviceList.getUniqueStr());
				mb.appendMessage(" 行号" + i + " " + deviceList.toString());
				return false;
			}
			i++;
		}
		return true;
	}

	private Properties configInit(Properties config, String configPath)
	{
		try
		{
			config = MiscTools.loadConfig(configPath);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return config;
	}
}
